let uniID = require('uni-id')
const error = require('error')
const db = uniCloud.database();
const config = require('uni-config-center/uni-id/config.json')
class method {
	constructor() {
		let weixin = config['mp-weixin'].oauth.weixin
		this.openid = weixin.appid
		this.secret = weixin.appsecret
	}
	// 微信登录
	async loginWeixin(event, context) {
		uniID = uniID.createInstance({
			context
		})
		const res = await uniID.loginByWeixin({
			code: event.data
		})
		// 写登录日志
		db.collection('uni-id-log').add(res)
		return res
	}
	// 补充填写相关信息
	async replenish(event, context) {
		uniID = uniID.createInstance({
			context
		})
		let res = await this.getuid(event.uniIdToken)
		if (!error(res.code)) return res
		const uniIDIns = uniID.createInstance({ // 创建uni-id实例，其上方法同uniID
			context: context,
			// config: {} // 完整uni-id配置信息，使用config.json进行配置时无需传此参数
		})
		let uid = res.uid
		let obj = {
			nickName: event.data.nickName,
			avatarUrl: event.data.avatarUrl,
			uid,
			mobile: event.data.mobile,
			my_invite_code: event.data.my_invite_code
		}

		if (!["", undefined].includes(obj.my_invite_code)) {
			obj.invite_time = Date.now()
		}

		for (let key in obj) {
			if (["", undefined].includes(obj[key])) {

				delete obj[key]
			}
		}

		res = await uniIDIns.updateUser(obj)
		return res
	}
	// 获取uid
	async getuid(uniIdToken) {

		return await uniID.getUserInfoByToken(uniIdToken);
	}
	// 获取用户信息
	async getUser(event, context) {
		uniID = uniID.createInstance({
			context
		})
		let res = await this.getuid(event.uniIdToken)
		if (!error(res.code)) return res
		let uid = res.uid
		res = await uniID.getUserInfo({
			uid
		})
		return res
	}
	// 获取手机号 登录获取 code  
	async codeGetMobile(event,context){
		uniID = uniID.createInstance({
			context
		})
		let res,sessionKey 
		res = await uniID.code2SessionWeixin(event.data.loginCode)
		
		sessionKey = res.sessionKey
		event.data.sessionKey = sessionKey
		res = await uniID.wxBizDataCrypt(event.data)
		
		return res
	}
	// 直接解码手机号
	async getMobile(event,context){
		let res 
		res = await uniID.wxBizDataCrypt(event.data)
		console.log(res,9877799999)
		return res
	}
}
module.exports = new method
